package com.naiterui.ehp.bs.wechat.controller;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.naiterui.ehp.bp.constants.PaQrCodeEnum;
import com.naiterui.ehp.bp.support.exception.BaseExceptionCodes;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.support.exception.PublicService;
import com.naiterui.ehp.bp.support.exception.ResponseVO;
import com.naiterui.ehp.bs.wechat.constants.WeChatConstant;
import com.naiterui.ehp.bs.wechat.protocol.params.CodeActionInfo;
import com.naiterui.ehp.bs.wechat.protocol.result.QrCodeResult;
import com.naiterui.ehp.bs.wechat.service.IAccessTokenService;
import com.naiterui.ehp.bs.wechat.utils.WeChatApiUtil;

/**
 * @author zhoupeipei
 * @date 2019-07-09 17:04
 * @since 1.0.0
 */
@RequestMapping("ap/inner/qrcode")
@RestController
public class InnerQrCodeController {
    private static final Logger LOGGER = LoggerFactory.getLogger(InnerQrCodeController.class);

    @Autowired
    IAccessTokenService accessTokenService;

    /**
     * @param codeType {@link PaQrCodeEnum.value}
     * @param scene    二维码场景标识
     *
     * @return
     *
     * @throws Exception
     */
    @RequestMapping("get")
    public ResponseVO<String> generateQrcode(String codeType,
                                             String scene) throws Exception {
        if (StringUtils.isBlank(codeType) || StringUtils.isBlank(scene)) {
            LOGGER.error("生成公众号二维码参数异常，codeType:{},scene:{},limit:{}", codeType, scene);
            throw new BusinessException(BaseExceptionCodes.PARAM_ERROR);
        }
        PaQrCodeEnum qrCodeEnum = PaQrCodeEnum.getByValue(codeType);
        String actionName = qrCodeEnum.getActionName();
        if (WeChatConstant.PaActionType.QR_LIMIT_STR_SCENE.equals(actionName) || WeChatConstant.PaActionType.QR_STR_SCENE.equals(actionName)) {
            QrCodeResult result = WeChatApiUtil.getQrCodeStr(accessTokenService.accessToken(), qrCodeEnum.getActionName(),
                    new CodeActionInfo.Scene(qrCodeEnum.getValue() + scene));
            //String qrCodeUrl = WeChatApiUtil.WECHAT_SHOW_QRCODE_URL + result.getTicket();
            return PublicService.returnResponseVO(BaseExceptionCodes.SUCCESS, result.getUrl());
        } else {
            LOGGER.info("暂不支持整型场景值二维码，qrCode:{}", qrCodeEnum);
            return PublicService.returnResponseVO(BaseExceptionCodes.SUCCESS, null);
        }
    }

}
